﻿namespace QuickMail.View.Controls
{
    using System;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Controls.Primitives;
    using System.Windows.Media.Animation;

    using DbWorker.DataModels;
    using Hardcodet.Wpf.TaskbarNotification;
    using QuickMail.BusinessLogic;
    using QuickMail.DataModels;
    using QuickMail.ViewModels;

    /// <summary>
    /// Interaction logic for QmBalloon.xaml
    /// </summary>
    public partial class QmBalloon
    {
        public delegate void ReadLetterHandler(LetterVm letterVm);
        public event ReadLetterHandler ReadLetterOnClick;

        private bool isClosing;
        private readonly LetterVm _letterVm;

        /// <summary>
        /// Creates new balloon
        /// </summary>
        public QmBalloon(LetterVm letterVm)
        {
            InitializeComponent();
            TitleFromTextBlock.Text = StaticFields.Lang.LetterBalloon.From;
            TitleFromTextBlock.Text = StaticFields.Lang.LetterBalloon.To;
            ReadLetterTextBlock.Text = StaticFields.Lang.LetterBalloon.ReadLetter;
            OpenFolderTextBlock.Text = StaticFields.Lang.LetterBalloon.OpenFolder;

            TaskbarIcon.AddBalloonClosingHandler(this, OnBalloonClosing);
            var sb = (Storyboard)Resources["FadeOut"];
            sb.Completed += OnFadeOutCompleted;

            _letterVm = letterVm;
            Load(letterVm);
        }

        /// <summary>
        /// Loads letter to the form.
        /// </summary>
        private void Load(LetterVm letterVm)
        {
            switch (letterVm.Type)
            {
                case LetterType.Outgoing:
                    StatusImage.Source = StaticFields.SendWhiteImage;
                    TitleTextBlock.Text = StaticFields.Lang.LetterBalloon.Sent;
                    HeaderGrid.Background = StaticFields.GreenColorBrush;
                    break;
                case LetterType.Incoming:
                    StatusImage.Source = StaticFields.ReceiveWhiteImage;
                    TitleTextBlock.Text = StaticFields.Lang.LetterBalloon.Received;
                    HeaderGrid.Background = StaticFields.GreenColorBrush;
                    break;
                case LetterType.NotSent:
                    StatusImage.Source = StaticFields.ErrorWhiteImage;
                    TitleTextBlock.Text = StaticFields.Lang.LetterBalloon.NotSent;
                    HeaderGrid.Background = StaticFields.ErrorTextColorBrush;
                    break;
            }

            FromTextBlock.Text = letterVm.From;
            ToTextBlock.Text = letterVm.To;
            SubjecTextBlock.Text = letterVm.Subject;

            AttachmentsStackPanel.Children.Clear();
            foreach (var fileMetadata in letterVm.FileVms)
            {
                AttachmentsStackPanel.Children.Add(new Button
                {
                    Style = (Style)Resources["FileButtonStyle"],
                    Tag = HelpWorker.GetFileImage(fileMetadata.Extention),
                    Content = fileMetadata.FileName,
                    ToolTip = fileMetadata.FileName,
                    CommandParameter = Path.Combine(StaticFields.ResourcesPath, 
                        _letterVm.Id.ToString(CultureInfo.InvariantCulture), fileMetadata.FileName)
                });
            }
        }

        /// <summary>
        /// By subscribing to the <see cref="TaskbarIcon.BalloonClosingEvent"/>
        /// and setting the "Handled" property to true, we suppress the popup
        /// from being closed in order to display the custom fade-out animation.
        /// </summary>
        private void OnBalloonClosing(object sender, RoutedEventArgs e)
        {
            e.Handled = true; //suppresses the popup from being closed immediately
            isClosing = true;
        }

        /// <summary>
        /// Resolves the <see cref="TaskbarIcon"/> that displayed
        /// the balloon and requests a close action.
        /// </summary>
        private void CloseBalloon_OnClick(object sender, RoutedEventArgs e)
        {
            //the tray icon assigned this attached property to simplify access
            TaskbarIcon taskbarIcon = TaskbarIcon.GetParentTaskbarIcon(this);
            taskbarIcon.CloseBalloon();
        }

        /// <summary>
        /// If the users hovers over the balloon, we don't close it.
        /// </summary>
        private void BalloonGrid_MouseEnter(object sender, MouseEventArgs e)
        {
            //if we're already running the fade-out animation, do not interrupt anymore
            //(makes things too complicated for the sample)
            if (isClosing) 
                return;

            //the tray icon assigned this attached property to simplify access
            TaskbarIcon taskbarIcon = TaskbarIcon.GetParentTaskbarIcon(this);
            taskbarIcon.ResetBalloonCloseTimer();
        }

        /// <summary>
        /// Closes the popup once the fade-out animation completed.
        /// The animation was triggered in XAML through the attached
        /// BalloonClosing event.
        /// </summary>
        private void OnFadeOutCompleted(object sender, EventArgs e)
        {
            var pp = (Popup)Parent;
            pp.IsOpen = false;
        }

        /// <summary>
        /// Opens folder in the explorer.
        /// </summary>
        private void OpenFolder_OnClick(object sender, RoutedEventArgs e)
        {
            Process.Start("explorer.exe", Path.Combine
                (StaticFields.ResourcesPath, _letterVm.Id.ToString(CultureInfo.InvariantCulture)));
        }

        /// <summary>
        /// Raises the event of reading the letter.
        /// </summary>
        private void ReadLetter_OnClick(object sender, RoutedEventArgs e)
        {
            if(ReadLetterOnClick != null)
                ReadLetterOnClick(_letterVm);
        }
    }
}
